<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Model\Spec;
use App\Model\SpecValue;
use Illuminate\Http\Request;

/**
 * 规格项管理
 */
class SpecController extends Controller
{
    /**
     * 定义模型
     */
    public $model;
    public $specValueModel;

    /**
     * 定义验证
     */
    public $validate;

    /**
     * 初始化控制器
     */
    public function __construct()
    {
        $this->model = (new Spec());
        $this->validate = (new \App\Validate\Admin\Spec());
        $this->specValueModel = (new SpecValue());
    }

    /**
     * 添加规格
     */
    public function add_spec(Request $request)
    {
        // 获取参数
        $only = ['spec_name', 'spec_value'];
        $params = $request->only($only);
        if ($params) {
            if (!$this->validate->check($params)) {
                $this->error($this->validate->getError());
            }
            // 判断规格组是否存在
            if (!$specId = $this->model->getSpecIdByName($params['spec_name'])) {
                // 新增规格组and规则值
                if ($this->model->add($params['spec_name'])
                    && $this->specValueModel->add($this->model['id'], $params['spec_value']))
                    return $this->success([
                        'spec_id' => (int)$this->model['id'],
                        'value_id' => (int)$this->specValueModel['id'],
                    ]);
                return $this->error();
            }
            //return ;
            // 判断规格值是否存在
            if ($specValueId = $this->specValueModel->getSpecValueIdByName($specId, $params['spec_value'])) {
                return $this->success([
                    'spec_id' => (int)$specId,
                    'value_id' => (int)$specValueId,
                ]);
            }
            // 添加规则值
            if ($this->specValueModel->add($specId, $params['spec_value']))
                return $this->success([
                    'spec_id' => (int)$specId,
                    'value_id' => (int)$this->specValueModel['id'],
                ]);
            return $this->error();
        }
        $this->error('参数不能为空');
    }
}
